package controller

import (
	"StrayAnimals/internal/model"
	"StrayAnimals/internal/service"
	"StrayAnimals/pkg/errorx"
	"StrayAnimals/pkg/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// Register 用户注册接口
func Register(c *gin.Context) {
	var userInput struct {
		Email    string `json:"email"`
		Password string `json:"password"`
		Captcha  string `json:"captcha"`
	}

	// 解析请求体
	if err := c.ShouldBindJSON(&userInput); err != nil {
		c.JSON(400, gin.H{
			"code":    401,
			"message": "参数错误；" + err.Error(),
		})
		return
	}

	// 验证邮箱格式
	if !utils.IsValidEmail(userInput.Email) {
		c.JSON(400, gin.H{
			"code":    402,
			"message": "邮箱格式不正确",
		})
		return
	}

	// 检查邮箱是否已注册
	isRegistered, err := service.IsEmailRegistered(userInput.Email)
	if err != nil {
		c.JSON(500, gin.H{
			"code":    501,
			"message": "系统错误，请稍后再试；" + err.Error(),
		})
		return
	}
	if isRegistered {
		c.JSON(400, gin.H{
			"code":    403,
			"message": "邮箱已被注册，请直接登录",
		})
		return
	}

	// 查询验证码并校验有效性
	storedCaptcha, err := service.CheckCaptcha(userInput.Email)
	if err != nil {
		if errors.Is(err, errorx.ErrCaptchaNotFound) {
			c.JSON(400, gin.H{
				"code":    404,
				"message": "验证码不存在/已过期，请重新获取验证码",
			})
		} else {
			c.JSON(500, gin.H{
				"code":    501,
				"message": "系统错误，注册失败，请稍后再试；" + err.Error(),
			})
		}
		return
	}

	// 校验验证码
	if userInput.Captcha != storedCaptcha {
		c.JSON(400, gin.H{
			"code":    406,
			"message": "验证码错误，请检查验证码",
		})
		return
	}

	// 检查是否填入密码
	if userInput.Password == "" {
		c.JSON(400, gin.H{
			"code":    406,
			"message": "密码为空，无法注册",
		})
		return
	}

	// 加密密码
	hashedPassword, err := service.EncryptPassword(userInput.Password)
	if err != nil {
		c.JSON(500, gin.H{
			"code":    501,
			"message": "系统错误，注册失败，请稍后再试；" + err.Error(),
		})
		return
	}

	// 创建新用户
	newUser := model.User{
		ID:        uuid.New().String(),
		Email:     userInput.Email,
		Password:  string(hashedPassword),
		Phone:     "",
		Username:  "",
		Gender:    "",
		Birthday:  "",
		Avatar:    "",
		IsManager: false,
	}
	if err := service.CreateNewUser(newUser); err != nil {
		c.JSON(500, gin.H{
			"code":    501,
			"message": "系统错误，注册失败，请稍后再试；" + err.Error(),
		})
		return
	}

	// 删除验证码记录（避免重复使用）
	service.DeleteCaptcha(userInput.Email)

	// 返回成功响应
	c.JSON(200, gin.H{
		"code":    200,
		"message": "注册成功，请登录",
	})
}
